{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Python Algorithmic Trading Cookbook"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Chapter 3: Fetching Financial Data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This Jupyter Notebook is created using Python version 3.8.2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "----"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Requirements"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can install the requirements for this Jupyter Notebook by executing the below cell"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install pyalgotrading"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "----"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Master Recipe\n",
    "\n",
    "The following code will help you set up the broker connection with Zerodha, which will be used by all the recipes in this chapter. Please make sure you have followed these steps before trying out any recipe. \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pyalgotrading.broker.broker_connection_zerodha import BrokerConnectionZerodha"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Installing package kiteconnect via pip. This may take a while...\n",
      "Please login to this link to generate your request token: https://kite.trade/connect/login?api_key=<your-api-key>&v=3\n"
     ]
    }
   ],
   "source": [
    "# Get the api_key and api_secret from broker. These are unique to you and will be used by the broker to identify your demat account.\n",
    "api_key = \"<your-api-key>\"\n",
    "api_secret = \"<your-api-secret>\"\n",
    "broker_connection = BrokerConnectionZerodha(api_key, api_secret)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Get the request token from the above URL\n",
    "request_token = \"<your-request-token>\"\n",
    "broker_connection.set_access_token(request_token)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "----"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Recipe 1: Fetching the list of Financial Instruments"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>instrument_token</th>\n",
       "      <th>exchange_token</th>\n",
       "      <th>tradingsymbol</th>\n",
       "      <th>name</th>\n",
       "      <th>last_price</th>\n",
       "      <th>expiry</th>\n",
       "      <th>strike</th>\n",
       "      <th>tick_size</th>\n",
       "      <th>lot_size</th>\n",
       "      <th>instrument_type</th>\n",
       "      <th>segment</th>\n",
       "      <th>exchange</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>544844550</td>\n",
       "      <td>2128299</td>\n",
       "      <td>EURINR20AUG79.2500CE</td>\n",
       "      <td>EURINR</td>\n",
       "      <td>0.0</td>\n",
       "      <td>2020-08-27</td>\n",
       "      <td>79.25</td>\n",
       "      <td>0.0025</td>\n",
       "      <td>1</td>\n",
       "      <td>CE</td>\n",
       "      <td>BCD-OPT</td>\n",
       "      <td>BCD</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>544838918</td>\n",
       "      <td>2128277</td>\n",
       "      <td>EURINR20AUG79.2500PE</td>\n",
       "      <td>EURINR</td>\n",
       "      <td>0.0</td>\n",
       "      <td>2020-08-27</td>\n",
       "      <td>79.25</td>\n",
       "      <td>0.0025</td>\n",
       "      <td>1</td>\n",
       "      <td>PE</td>\n",
       "      <td>BCD-OPT</td>\n",
       "      <td>BCD</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>544788742</td>\n",
       "      <td>2128081</td>\n",
       "      <td>EURINR20AUG79.5000CE</td>\n",
       "      <td>EURINR</td>\n",
       "      <td>0.0</td>\n",
       "      <td>2020-08-27</td>\n",
       "      <td>79.50</td>\n",
       "      <td>0.0025</td>\n",
       "      <td>1</td>\n",
       "      <td>CE</td>\n",
       "      <td>BCD-OPT</td>\n",
       "      <td>BCD</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>544782342</td>\n",
       "      <td>2128056</td>\n",
       "      <td>EURINR20AUG79.5000PE</td>\n",
       "      <td>EURINR</td>\n",
       "      <td>0.0</td>\n",
       "      <td>2020-08-27</td>\n",
       "      <td>79.50</td>\n",
       "      <td>0.0025</td>\n",
       "      <td>1</td>\n",
       "      <td>PE</td>\n",
       "      <td>BCD-OPT</td>\n",
       "      <td>BCD</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>544739078</td>\n",
       "      <td>2127887</td>\n",
       "      <td>EURINR20AUG79.7500CE</td>\n",
       "      <td>EURINR</td>\n",
       "      <td>0.0</td>\n",
       "      <td>2020-08-27</td>\n",
       "      <td>79.75</td>\n",
       "      <td>0.0025</td>\n",
       "      <td>1</td>\n",
       "      <td>CE</td>\n",
       "      <td>BCD-OPT</td>\n",
       "      <td>BCD</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>65292</th>\n",
       "      <td>1945089</td>\n",
       "      <td>7598</td>\n",
       "      <td>ZODJRDMKJ-BE</td>\n",
       "      <td>ZODIAC JRD MKJ-</td>\n",
       "      <td>0.0</td>\n",
       "      <td></td>\n",
       "      <td>0.00</td>\n",
       "      <td>0.0500</td>\n",
       "      <td>1</td>\n",
       "      <td>EQ</td>\n",
       "      <td>NSE</td>\n",
       "      <td>NSE</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>65293</th>\n",
       "      <td>2916865</td>\n",
       "      <td>11394</td>\n",
       "      <td>ZOTA</td>\n",
       "      <td>ZOTA HEALTH CARE</td>\n",
       "      <td>0.0</td>\n",
       "      <td></td>\n",
       "      <td>0.00</td>\n",
       "      <td>0.0500</td>\n",
       "      <td>1</td>\n",
       "      <td>EQ</td>\n",
       "      <td>NSE</td>\n",
       "      <td>NSE</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>65294</th>\n",
       "      <td>7436801</td>\n",
       "      <td>29050</td>\n",
       "      <td>ZUARI</td>\n",
       "      <td>ZUARI AGRO CHEMICALS</td>\n",
       "      <td>0.0</td>\n",
       "      <td></td>\n",
       "      <td>0.00</td>\n",
       "      <td>0.0500</td>\n",
       "      <td>1</td>\n",
       "      <td>EQ</td>\n",
       "      <td>NSE</td>\n",
       "      <td>NSE</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>65295</th>\n",
       "      <td>979713</td>\n",
       "      <td>3827</td>\n",
       "      <td>ZUARIGLOB</td>\n",
       "      <td>ZUARI GLOBAL</td>\n",
       "      <td>0.0</td>\n",
       "      <td></td>\n",
       "      <td>0.00</td>\n",
       "      <td>0.0500</td>\n",
       "      <td>1</td>\n",
       "      <td>EQ</td>\n",
       "      <td>NSE</td>\n",
       "      <td>NSE</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>65296</th>\n",
       "      <td>4514561</td>\n",
       "      <td>17635</td>\n",
       "      <td>ZYDUSWELL</td>\n",
       "      <td>ZYDUS WELLNESS</td>\n",
       "      <td>0.0</td>\n",
       "      <td></td>\n",
       "      <td>0.00</td>\n",
       "      <td>0.0500</td>\n",
       "      <td>1</td>\n",
       "      <td>EQ</td>\n",
       "      <td>NSE</td>\n",
       "      <td>NSE</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>65297 rows × 12 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "       instrument_token exchange_token         tradingsymbol  \\\n",
       "0             544844550        2128299  EURINR20AUG79.2500CE   \n",
       "1             544838918        2128277  EURINR20AUG79.2500PE   \n",
       "2             544788742        2128081  EURINR20AUG79.5000CE   \n",
       "3             544782342        2128056  EURINR20AUG79.5000PE   \n",
       "4             544739078        2127887  EURINR20AUG79.7500CE   \n",
       "...                 ...            ...                   ...   \n",
       "65292           1945089           7598          ZODJRDMKJ-BE   \n",
       "65293           2916865          11394                  ZOTA   \n",
       "65294           7436801          29050                 ZUARI   \n",
       "65295            979713           3827             ZUARIGLOB   \n",
       "65296           4514561          17635             ZYDUSWELL   \n",
       "\n",
       "                       name  last_price      expiry  strike  tick_size  \\\n",
       "0                    EURINR         0.0  2020-08-27   79.25     0.0025   \n",
       "1                    EURINR         0.0  2020-08-27   79.25     0.0025   \n",
       "2                    EURINR         0.0  2020-08-27   79.50     0.0025   \n",
       "3                    EURINR         0.0  2020-08-27   79.50     0.0025   \n",
       "4                    EURINR         0.0  2020-08-27   79.75     0.0025   \n",
       "...                     ...         ...         ...     ...        ...   \n",
       "65292       ZODIAC JRD MKJ-         0.0                0.00     0.0500   \n",
       "65293      ZOTA HEALTH CARE         0.0                0.00     0.0500   \n",
       "65294  ZUARI AGRO CHEMICALS         0.0                0.00     0.0500   \n",
       "65295          ZUARI GLOBAL         0.0                0.00     0.0500   \n",
       "65296        ZYDUS WELLNESS         0.0                0.00     0.0500   \n",
       "\n",
       "       lot_size instrument_type  segment exchange  \n",
       "0             1              CE  BCD-OPT      BCD  \n",
       "1             1              PE  BCD-OPT      BCD  \n",
       "2             1              CE  BCD-OPT      BCD  \n",
       "3             1              PE  BCD-OPT      BCD  \n",
       "4             1              CE  BCD-OPT      BCD  \n",
       "...         ...             ...      ...      ...  \n",
       "65292         1              EQ      NSE      NSE  \n",
       "65293         1              EQ      NSE      NSE  \n",
       "65294         1              EQ      NSE      NSE  \n",
       "65295         1              EQ      NSE      NSE  \n",
       "65296         1              EQ      NSE      NSE  \n",
       "\n",
       "[65297 rows x 12 columns]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "instruments = broker_connection.get_all_instruments()\n",
    "instruments"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Recipe 2: Attributes of a Financial Instrument"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['instrument_token',\n",
       " 'exchange_token',\n",
       " 'tradingsymbol',\n",
       " 'name',\n",
       " 'last_price',\n",
       " 'expiry',\n",
       " 'strike',\n",
       " 'tick_size',\n",
       " 'lot_size',\n",
       " 'instrument_type',\n",
       " 'segment',\n",
       " 'exchange']"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# All the attributes of financial instruments provided by the broker\n",
    "list(instruments.columns)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Recipe 3: Expiry of Financial Instruments"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "instrument1 = broker_connection.get_instrument('NSE', 'TATASTEEL')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Instrument expires: False\n"
     ]
    }
   ],
   "source": [
    "print(f'Instrument expires: {instrument1.will_expire()}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "instrument2 = broker_connection.get_instrument('NFO-FUT', 'TATASTEEL20AUGFUT')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Instrument expires: True\n"
     ]
    }
   ],
   "source": [
    "print(f'Instrument expires: {instrument2.will_expire()}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Expiry date: 2020-08-27\n"
     ]
    }
   ],
   "source": [
    "print(f'Expiry date: {instrument2.expiry}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Recipe 4: Circuit Limits of a Financial Instrument"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Lower circuit limit: 315.9\n",
      "Upper circuit limit: 386\n"
     ]
    }
   ],
   "source": [
    "lower_circuit_limit, upper_circuit_limit = broker_connection.get_circuit_limits(instrument1)\n",
    "print(f'Lower circuit limit: {lower_circuit_limit}')\n",
    "print(f'Upper circuit limit: {upper_circuit_limit}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Recipe 5: Market depth of a Financial Instrument"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Buy Market Depth:\n",
      "  orders   price  quantity\n",
      "0       1  350.05         1\n",
      "1      16  350.00     43294\n",
      "2       5  349.95      1250\n",
      "3       8  349.90      3134\n",
      "4       5  349.85      1078\n",
      "Sell Market Depth:\n",
      "  orders   price  quantity\n",
      "0       1  350.10        25\n",
      "1       7  350.15      1367\n",
      "2      13  350.20      4654\n",
      "3      13  350.25      2977\n",
      "4      21  350.30      5798\n"
     ]
    }
   ],
   "source": [
    "buy_market_depth, sell_market_depth = broker_connection.get_market_depth(instrument1)\n",
    "print(f'Buy Market Depth:\\n{buy_market_depth}')\n",
    "print(f'Sell Market Depth:\\n{sell_market_depth}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Recipe 6: Total Pending Buy Quantity of a Financial Instrument"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Total pending BUY quantity: 1319590\n"
     ]
    }
   ],
   "source": [
    "total_pending_buy_quantity = broker_connection.get_total_pending_buy_quantity(instrument1)\n",
    "print(f'Total pending BUY quantity: {total_pending_buy_quantity}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Recipe 7: Total Pending Sell Quantity of a Financial Instrument"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Total pending SELL quantity: 968602\n"
     ]
    }
   ],
   "source": [
    "total_pending_sell_quantity = broker_connection.get_total_pending_sell_quantity(instrument1)\n",
    "print(f'Total pending SELL quantity: {total_pending_sell_quantity}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Recipe 8: Total Volume traded for the day of a Financial Instrument"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Total Volume for the day so far: 24416975\n"
     ]
    }
   ],
   "source": [
    "total_volume_day = broker_connection.get_total_volume_day(instrument1)\n",
    "print(f'Total Volume for the day so far: {total_volume_day}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Recipe 9: Last Traded Price of a Financial Instrument"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Last traded price: 350.95\n"
     ]
    }
   ],
   "source": [
    "ltp = broker_connection.get_ltp(instrument1)\n",
    "print(f'Last traded price: {ltp}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Recipe 10: Last Traded Time of a Financial Instrument"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Last traded time: 2020-07-17 14:42:54\n"
     ]
    }
   ],
   "source": [
    "ltt = broker_connection.get_ltt(instrument1)\n",
    "print(f'Last traded time: {ltt}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Recipe 11: Last Traded Quantity of a Financial Instrument"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Last traded quantity: 19\n"
     ]
    }
   ],
   "source": [
    "ltq = broker_connection.get_ltq(instrument1)\n",
    "print(f'Last traded quantity: {ltq}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Recipe 12: The recorded Open price of the day of a Financial Instrument"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Open price today: 346\n"
     ]
    }
   ],
   "source": [
    "open_price_day = broker_connection.get_open_price_day(instrument1)\n",
    "print(f'Open price today: {open_price_day}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Recipe 13: The recorded Highest price of the day of a Financial Instrument"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Highest price today: 356.8\n"
     ]
    }
   ],
   "source": [
    "high_price_day = broker_connection.get_high_price_day(instrument1)\n",
    "print(f'Highest price today: {high_price_day}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Recipe 14: The recorded Lowest price of the day of a Financial Instrument"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Lowest price today: 345.15\n"
     ]
    }
   ],
   "source": [
    "low_price_day = broker_connection.get_low_price_day(instrument1)\n",
    "print(f'Lowest price today: {low_price_day}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Recipe 15: The recorded Close price of the last traded day of a Financial Instrument"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Close price of last trading day: 341.65\n"
     ]
    }
   ],
   "source": [
    "close_price_last_day = broker_connection.get_close_price_last_day(instrument1)\n",
    "print(f'Close price of last trading day: {close_price_last_day}')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
